package com.yimi.yinhepda.utils;

import android.content.Context;
import android.util.Log;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @author: lj
 * Date: 2019/11/16 17:10
 * Description:
 */
public class GzipUtil {
    public static final String GZIP_ENCODE_UTF_8 = "UTF-8";

    public static final String GZIP_ENCODE_ISO_8859_1 = "ISO-8859-1";

    /**
     * 字符串压缩为GZIP字节数组
     *
     * @param str
     * @param encoding
     * @return
     */
    public static byte[] compress(String str, String encoding) {
        if (str == null || str.length() == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip;
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes(encoding));
            gzip.close();
        } catch (IOException e) {
            Log.e("gzip compress error.", e.getMessage());
        }
        return out.toByteArray();
    }

    /**
     * Gzip  byte[] 解压成字符串
     *
     * @param bytes
     * @return
     */
    public static String uncompressToString(byte[] bytes) {
        return uncompressToString(bytes, GZIP_ENCODE_ISO_8859_1);
    }


    /**
     * Gzip  byte[] 解压成字符串
     *
     * @param bytes
     * @param encoding
     * @return
     */
    public static String uncompressToString(byte[] bytes, String encoding) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        try {
            GZIPInputStream ungzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = ungzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toString(encoding);
        } catch (IOException e) {
            Log.e("gzip compress error.", e.getMessage());
        }
        return null;
    }

    /**
     * 判断byte[]是否是Gzip格式
     *
     * @param data
     * @return
     */
    public static boolean isGzip(byte[] data) {
        int header = (int) ((data[0] << 8) | data[1] & 0xFF);
        return header == 0x1f8b;
    }

    /**
     * 解压缩
     */
    public static String uncompress(String str) {
        try {
            if (str == null || str.length() == 0) {
                return str;
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ByteArrayInputStream in = new ByteArrayInputStream(str
                    .getBytes("ISO-8859-1"));
            GZIPInputStream gunzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            // toString()使用平台默认编码，也可以显式的指定如toString(&quot;GBK&quot;)
            return out.toString("GBK");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String uncompress(String str, String encoding) {
        try {
            if (str == null || str.length() == 0) {
                return str;
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ByteArrayInputStream in = new ByteArrayInputStream(str
                    .getBytes(encoding));
            GZIPInputStream gunzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toString(encoding);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] uncompress(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        try {
            GZIPInputStream ungzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = ungzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }

    public static boolean uncompressZip4j(String zipFilePath, String filePath, String name) {
        return uncompressZip4j(zipFilePath,filePath,name,"123654");
    }

    public static boolean uncompressZip4j(String zipFilePath, String filePath, String name, String pwd) {
        try {
            ZipFile zipFile = new ZipFile(zipFilePath);
            //设置编码格式（支持中文）
            zipFile.setFileNameCharset("GBK");
            //检查输入的zip文件是否是有效的zip文件
            if (!zipFile.isValidZipFile()) {
                return false;
            }
            if (zipFile.isEncrypted()) {
                zipFile.setPassword(pwd);
            }
            FileHeader fh;
            for (int i = 0; i < zipFile.getFileHeaders().size(); i++) {
                fh = (FileHeader) zipFile.getFileHeaders().get(i);
                fh.setFileName(name);
                zipFile.extractFile(fh, filePath);
            }
//            File file = new File(zipFilePath);
//            if (file.exists()) {
//                file.delete();
//            }
            return true;

        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取assets文件路径
     * @param context
     * @param filePath
     * @return
     */
    public static String getAssetsPath(Context context, String filePath) {
        InputStream abpath = context.getClass().getResourceAsStream("/assets" + filePath);
        try {
            return new String(InputStreamToByte(abpath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] InputStreamToByte(InputStream is) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }
}
